import { constantRoutes } from '@/router'
import {
  getMenusTreeWithResources,
  getPermissionCodes,
  getDictMap,
} from '@/api/base'
import { getCoreSystemConfigAll } from '@/api/core'
import Cookies from 'js-cookie'
// import lazyLoad from '@/router/lazyLoad'
import _ from 'lodash'
let modules = import.meta.glob('../../views/**/*.vue')

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  const res = []
  if (routes.length <= 0) {
    return
  }
  routes.forEach((item) => {
    if (item.code !== 'dashboard') {
      if (item.url) {
        let tmp = {
          path: item.url,
          name: item.resourceCode,
          component:
            modules[/* @vite-ignore */ `../../views${item.url}/index.vue`],
          meta: {
            title: item.name,
            icon: item.icon,
          },
        }
        res.push(tmp)
      }
      if (item.children) {
        filterAsyncRoutes(item.children).forEach((item) => {
          res.push(item)
        })
        return
      }
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: [],
  permissionCodes: [],
  dict: {},
  systemConfig: {},
  defaultMenus: [],
}

const mutations = {
  SET_ADD_ROUTES: (state, routes) => {
    state.addRoutes = constantRoutes.concat(routes)
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  },
  RESET_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
    state.permissionCodes = []
  },
  SET_PERMISSIONS_CODES: (state, permissions) => {
    state.permissionCodes = permissions
  },
  SET_DICT: (state, data) => {
    state.dict = data
  },
  SYSTEM_CONFIG: (state, data) => {
    state.systemConfig = data
  },
  SET_Menus: (state, data) => {
    state.defaultMenus = data
  },
}

const actions = {
  generateRoutes({ dispatch, commit }) {
    return new Promise((resolve, reject) => {
      let accessedRoutes = []
      // let asyncRoutes = []
      let params = {
        userId: JSON.parse(Cookies.get('userInfo')).user.id,
        status: 1,
      }
      getMenusTreeWithResources(params)
        .then((response) => {
          if (response && response.success) {
            //let data =  _.cloneDeep(response.data)
            commit('SET_Menus', response.data)
            let { data } = _.cloneDeep(response)
            data = data.filter(
              (item) => item.code !== 'app' && item.code !== 'pda'
            )
            let arr = [
              // {
              //   code: 'base',
              //   disabled: false,
              //   icon: 'icon-nav-system-set',
              //   id: 1,
              //   name: '控制台',
              //   parentId: -1,
              //   resourceCode: 'Dashboard',
              //   spread: false,
              //   type: 'menu',
              //   url: '/dashboard',
              // },
            ]
            accessedRoutes = filterAsyncRoutes(data)
            arr = arr.concat(data)
            constantRoutes[0].children =
              constantRoutes[0].children.concat(accessedRoutes)
            dispatch('getDictMap')
            dispatch('getCoreSystemConfig')
            commit('SET_ADD_ROUTES', constantRoutes)
            commit('SET_ROUTES', arr)
            resolve(constantRoutes)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  //获取用户按钮权限集合
  getUserPermissionCodes({ commit }) {
    return new Promise((resolve, reject) => {
      let params = {
        userId: JSON.parse(Cookies.get('userInfo')).user.id,
        menuType: 0,
      }
      getPermissionCodes(params)
        .then((resp) => {
          if (resp && resp.success) {
            commit('SET_PERMISSIONS_CODES', resp.data)
          }
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  getDictMap({ commit }) {
    getDictMap().then((resp) => {
      if (resp && resp.success) {
        let data = resp.data
        console.log(data)
        sessionStorage.setItem('dictMap', JSON.stringify(data))
        commit('SET_DICT', data)
      }
    })
  },
  resetRoutes({ commit }) {
    commit('RESET_ROUTES')
  },
  getCoreSystemConfig({ commit }) {
    /*
    .    数量操作模式 qty_operate_mode：0整数模式，2自动算出小数，1手动输入小数
    .    个体操作扫码切换提示保存当前操作 individual_scan_chang：0不提示，1提示
    .    价格精度保留策略 price_retention_strategy：0取整，1进一，2四舍五入
    .    数量展示精度保留策略 qty_show_retention_strategy： 0取整，1进一，2四舍五入
    .    数量计算精度保留策略 qty_calc_retention_strategy： 0取整，1进一，2四舍五入
    .    数量计算精度 qty_calc_precision
    .    数量展示精度 qty_show_precision
    .    价格精度 price_precision
    .    条码类型 code_type：1无码，2系统唯一码，3原厂码，4批次码
    .    系统名称 system_name：系统名称
    .    供应商预期到货天数(天) expect_delivery_day：供应商预期到货天数(天)
    */
    getCoreSystemConfigAll().then((res) => {
      if (res && res.success && res.data && res.data.length) {
        let data = res.data
        let obj = {}
        data.forEach((item) => {
          if (item.value.indexOf(',') !== -1) {
            obj[item.systemConfigCode] = item.value
          } else if (
            item.systemConfigCode === 'system_name' ||
            item.systemConfigCode === 'websocket_ip_port' ||
            item.systemConfigCode === 'connect_purchase_platform_system'
          ) {
            obj[item.systemConfigCode] = item.value
          } else {
            obj[item.systemConfigCode] = Number(item.value)
          }
        })
        commit('SYSTEM_CONFIG', obj)
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
